package com.yjd.bi.etl.business.service;

import java.util.Calendar;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.yjd.bi.etl.comm.BaseService;
import com.yjd.bi.etl.comm.Constants;
import com.yjd.bi.etl.sql.BusinessSqlConstants;
import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.util.BiUtil;
import com.yjd.comm.util.DateUtil;

@Component("investInfoService")
public class InvestInfoService extends BaseService{

	private static final int  DAYOFSECOND = 86400;
	
	public void process() throws Exception{
		BiDatabaseInfoModel model = this.getBiDatabaseInfoModel();
		JdbcTemplate jt = BiUtil.getJdbcTemplate(model);

		// 统计历史数据
		long maxDate = jt.queryForInt(BusinessSqlConstants.GET_MAX_INVEST_TATISTIC_DATE);
		
		if (maxDate == 0) {
			// 没有统计过，取网站上线运营的第一天 平台上线时间（2013年12月21日00：00：00）
			maxDate = Constants.INITIALIZATION_TIME;
		}else{
			maxDate = DateUtil.dateStringToTimestamp(maxDate+"",
					DateUtil.PATTERN_yyyyMMdd)+DAYOFSECOND;
		}
		
		//获取当天的0点的时间戳
		Calendar todayStart = Calendar.getInstance();  
        todayStart.set(Calendar.HOUR_OF_DAY, 0);  
        todayStart.set(Calendar.MINUTE, 0);  
        todayStart.set(Calendar.SECOND, 0);  
        todayStart.set(Calendar.MILLISECOND, 0);
        long todayTime = todayStart.getTime().getTime()/1000L; 
		
		while (maxDate  < todayTime ) {
			// 统计前一天的用户数据
			statisticLastData(maxDate, jt);
			maxDate += DAYOFSECOND;// 加一天和当前时间比较，如果小于当前时间则继续统计
			
		}
	}

	private void statisticLastData(long maxDate, JdbcTemplate jt) {
		long beginDate = maxDate;
		long endDate = beginDate + DAYOFSECOND - 1;
		Long staticsDate = Long.parseLong(DateUtil.timestampToDateString(
				beginDate, DateUtil.PATTERN_yyyyMMdd));
		// 成交笔数， 投资项目，按照实际满标时间
		int invest_amount = jt.queryForObject(BusinessSqlConstants.GET_INVEST_AMOUNT,new Object[] { beginDate, endDate},Integer.class);
		// 投资金额
		int invest_price = jt.queryForObject(BusinessSqlConstants.GET_INVEST_PRICE,new Object[] { beginDate, endDate},Integer.class);
		
		//待回收金额（不含代偿余额）－投资项目
		double recover_price = jt.queryForObject(BusinessSqlConstants.GET_RECOVER_PRICE,new Object[] { endDate,endDate,endDate},Double.class);
		
		//待回收金额（含代偿余额）－投资项目
		double recover_price1 = jt.queryForObject(BusinessSqlConstants.GET_RECOVER_PRICE1,new Object[] { endDate,endDate},Double.class);
		
		try{
			jt.update(BusinessSqlConstants.INVESTINFO_INSERTSQL,invest_price,invest_amount,recover_price,recover_price1,staticsDate);
		}catch(Exception e){
			logger.info("批量处理插入失败，处理sql:"+BusinessSqlConstants.INVESTINFO_INSERTSQL+"处理数据:"+staticsDate+"错误信息:"+e);
		}
		
	}
	
}
